/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import static client.RefManager.*;

/**
 *
 * @author zero.one
 */
public class NachrichtEmpfangenThread extends Thread {

    int BUFFER_SIZE = 1024;

    public NachrichtEmpfangenThread() {
    }

    public void run() {
        String receiveString = "";
        DatagramSocket clientSocket;
        try {
            clientSocket = new DatagramSocket(50001);
        } catch (SocketException ex) {
            System.err.println("UDP-Thread konnte kein Socket erstellen");
            return;
        }
        /* Paket für den Empfang erzeugen */
        byte[] receiveData = new byte[BUFFER_SIZE];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, BUFFER_SIZE);
        while (true) {
            try {
                /* Warte auf Empfang des Antwort-Pakets auf dem eigenen Port */
                clientSocket.receive(receivePacket);

                /* Paket wurde empfangen --> auspacken und Inhalt anzeigen */
                receiveString = new String(receivePacket.getData(), 0, receivePacket.getLength(), "UTF-8");
                String adress = receivePacket.getAddress().getHostName();
                String [] checkAnswer = receiveString.split(":");
                String username = checkAnswer[0];
                if(client.userMap.containsKey(adress) &&
                    client.userMap.get(adress).equals(username) && checkAnswer[1].length() <= 102){
                    gui.showMessageInGUI(receiveString);
                }
                else{
                    System.err.println("Ungültige Nachricht Empfangen: "+ receiveString);
                }
            } catch (IOException e) {
                System.err.println("Connection aborted by server!");
                clientSocket.close();
                return;
            }
        }
    }
}
